<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :default-config="toolbarConfig"
      :mode="mode"
    />
    <Editor
      v-model="valueHtml"
      style="height: 500px; overflow-y: hidden"
      :default-config="editorConfig"
      :mode="mode"
      @on-created="handleCreated"
      @on-change="handleChange"
      @on-blur="handleBlur"
    />
  </div>
</template>

<script lang="ts">
  import '@wangeditor/editor/dist/css/style.css'; // 引入 css

  import {
    onBeforeUnmount,
    ref,
    shallowRef,
    onMounted,
    nextTick,
    watch,
  } from 'vue';
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

  export default {
    components: { Editor, Toolbar },
    props: {
      modelValue: {
        type: String,
        default: '',
      },
    },
    emits: ['update:modelValue'],
    setup(props: any, { emit }: any) {
      const mode = ref('simple');
      // 编辑器实例，必须用 shallowRef
      const editorRef = shallowRef();

      // 内容 HTML
      const valueHtml = ref('');
      watch(
        () => props.modelValue,
        (val) => {
          if (val.length <= 0) {
            return;
          }
          valueHtml.value = val;
        },
        {
          deep: true,
          immediate: true,
        }
      );
      // 模拟 ajax 异步获取内容
      onMounted(() => {
        nextTick(() => {
          valueHtml.value = props.modelValue;
        });
      });

      const toolbarConfig = {
        excludeKeys: ['fullScreen', 'todo'],
      };
      const editorConfig = { placeholder: '请输入内容...' };

      // 组件销毁时，也及时销毁编辑器
      onBeforeUnmount(() => {
        const editor = editorRef.value;
        if (editor == null) return;
        editor.destroy();
      });

      const handleCreated = (editor: { blur: () => void }) => {
        editor.blur();
        editorRef.value = editor; // 记录 editor 实例，重要！
      };
      const handleChange = (value: { getHtml: () => any }) => {
        emit('update:modelValue', value.getHtml());
      };
      const handleBlur = (value: { getHtml: () => any }) => {
        emit('update:modelValue', value.getHtml());
      };
      // eslint-disable-next-line @typescript-eslint/no-empty-function

      return {
        editorRef,
        valueHtml,
        mode, // 或 'simple'
        toolbarConfig,
        editorConfig,
        handleCreated,
        handleChange,
        handleBlur,
      };
    },
  };
</script>
